/*
 * Copyright (c) 2020-2021. the original authors and DEPSEA.ORG
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.depsea.butterfly.web.result;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.depsea.butterfly.common.error.ErrorInfo;
import org.depsea.butterfly.common.error.ErrorStatus;

/**
 * 基础应答信息
 *
 * @author jaune
 * @since 1.0.0
 */
@ApiModel
@Schema(name = "应答信息")
@NoArgsConstructor
@Data
public abstract class BaseResponseBean<T> {

    /**
     * 业务处理是否成功
     */
    @ApiModelProperty(value = "业务处理是否成功")
    @Schema(name = "业务处理是否成功", example = "true")
    private boolean success;

    /**
     * 真实的Http状态码，默认200
     *
     * <p>如果是业务异常，应该为200，因为一般情况下业务异常是当处理业务时因为某些条件不满足或者数据验证未通过等情况，这时候返回的应是给用户
     * 友好的提示信息，待用户进一步修改后重新提交
     * </p>
     *
     * <p>针对404、401、403以及其他的非业务异常，一般建议返回对应的真实的状态码</p>
     *
     * <p>此字段为一个参考字段，非必要，核心字段应该为 {@link #errorCode}</p>
     */
    @ApiModelProperty(value = "真实的Http状态码")
    @Schema(name = "真实的Http状态码", example = "200")
    private int status = 200;

    /**
     * 错误编码
     */
    @ApiModelProperty(value = "错误编码")
    @Schema(name = "错误编码", example = "ERR_1001")
    private String errorCode;

    /**
     * 消息（成功消息或失败消息）
     */
    @ApiModelProperty(value = "消息")
    @Schema(name = "消息", example = "Token失效，请重新登录")
    private String message;

    /**
     * 扩展数据
     */
    @ApiModelProperty(value = "扩展数据")
    @Schema(name = "扩展数据")
    private T extension;

    protected BaseResponseBean(boolean success, int status) {
        this.success = success;
        this.status = status;
    }

    protected BaseResponseBean(String errorCode, String message) {
        this.errorCode = errorCode;
        this.message = message;
        this.success = false;
    }

    protected BaseResponseBean(ErrorInfo errorInfo) {
        this(errorInfo.getErrorCode(), errorInfo.getErrorMessage());
        if (errorInfo instanceof ErrorStatus) {
            this.status = ((ErrorStatus) errorInfo).getStatus();
        }
    }
}
